using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Magnet : MonoBehaviour
{
    public bool enable = false;
    private void Start()
    {
        MagnetManager.instance.MagnetsRb.Add(GetComponent<Rigidbody2D>());
    }
    private void Update()
    {
        if (enable)
        {
            foreach (var magnet in MagnetManager.instance.MagnetsRb)
            {
                AddMagnetism(magnet);
            }
        }
    }
    void AddMagnetism(Rigidbody2D rb)
    {
        var distance = Vector2.Distance(rb.transform.position,transform.position)+1;
        rb.AddForce((transform.position - rb.transform.position).normalized * MagnetManager.instance.magnetForce /
                    distance,ForceMode2D.Force);
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        
        if (other.gameObject.name == "Character")
        {
            enable = true;
        }
    }

    private void OnCollisionExit2D(Collision2D other)
    {
        if (other.gameObject.name == "Character")
        {
            enable = false;
        }
    }
}